/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 *
 *PmCustomerController
 * 客户档案
 *
 * 修改纪录
 * 2020-05-11 版本：1.0 wushenghong 创建。
 * @version 版本：1.0
 * @author 作者：wushenghong
 * 创建日期：2020-05-11
 */

package com.topscomm.pm.controller;

import com.alibaba.fastjson.JSONObject;
import com.topscomm.cbo.pojo.CboApprovalNodeInsEntity;
import com.topscomm.cbo.pojo.CboOrgEntity;
import com.topscomm.cbo.service.ICboOrgService;
import com.topscomm.cbo.service.impl.CboApprovalNodeInsService;
import com.topscomm.pm.PmSystemConst;
import com.topscomm.pm.controller.auto.PmCustomerControllerAuto;
import com.topscomm.pm.pojo.PmContractEntity;
import com.topscomm.pm.service.impl.PmContractService;
import com.topscomm.pub.util.*;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.ITapService;
import com.topscomm.tap.common.ParameterCache;
import java.util.ArrayList;
import java.util.HashMap;
import net.sf.jsqlparser.expression.StringValue;
import org.apache.commons.collections4.Put;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.web.client.RestTemplate;

/**
 * @author: wushenghong
 * @date: 2020-05-11
 * @description:客户档案Controller
 * @modify:
 */
@RestController
@RequestMapping("pm/customer")
public class PmCustomerController extends PmCustomerControllerAuto implements IPmCustomerController {
	@Resource(name="cboOrgService")
	private ICboOrgService cboOrgService;
	@Autowired
	private PmContractService pmContractService;
	@Autowired
	private CboApprovalNodeInsService cboApprovalNodeInsService;
	/**
	 * @author: wushenghong
	 * @date: 2020-05-11
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" 1=1 ");
		if (paraMap.containsKey("qry_customercategory")) {
			String value = paraMap.get("qry_customercategory").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and category = '{0}'", value);
		}
		if (paraMap.containsKey("qry_companyname")) {
			String value = paraMap.get("qry_companyname").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and name like '%{0}%'", value);
		}
		if (paraMap.containsKey("qry_username")) {
			String value = paraMap.get("qry_username").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and username like '%{0}%'", value);
		}
		return sql.toString();
	}

	/**
	 * @author: wushenghong
	 * @date: 2020-05-11
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		super.refList(paraMap);
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Query query = new Query(paraMap);
			// 添加有效过滤
			String sqlWhere =this.spellRefListSql(paraMap) + "and enabled = 1";
			int totalCount = ((ITapService)this.service).getCount(sqlWhere);
			List<Map<String, Object>> tempList = null;
			if (query.getPageSize() > 0) {
				tempList = ((ITapService)this.service).queryMapForPage(sqlWhere, query.getCurrentPage(), query.getPageSize(), query.getSidx(), query.getSord());
			} else {
				tempList = ((ITapService)this.service).queryMapByWhere(sqlWhere);
			}

			((ITapService)this.service).setDispFields(tempList);
			Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(page);
		} catch (Exception var7) {
			return this.handleControllerException(var7);
		}
	}

	/**
	 *
	 * @description: 提交审批前
	 * @param dataMap
	 * @param paraMap
	 * @throws Exception
	 * @author: wushenghong
	 * @date: 2020-05-11
	 * @modify:
	 */
	@Override
	protected void beforeSubmit(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
		super.beforeSubmit(dataMap, paraMap);
		StringBufferProxy mailtitle = new StringBufferProxy();
		mailtitle.appendSingle("{0}{1}于{2}提交客户档案申请,单据编号{3}! ", dataMap.get("dispdeptcode"), dataMap.get("username"), DateUtil.dateToString(new Date(), "yyyy-MM-dd"), dataMap.get("docno"));
		dataMap.put("maintitle", mailtitle.toString());
	}
	/**
	 *
	 * @description: 部门关联组织接口
	 * @param paraMap
	 * @author: wushenghong
	 * @date: 2020-05-11
	 * @modify:
	 */
	@GetMapping(value = "/queryOrgByDeptId")
	public ResponseResult<Object> queryOrgByDeptId(@RequestParam Map<String, Object> paraMap) {
		String deptId = ConvertUtil.convertToString(paraMap.get("deptId"));
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle("id in (select orgid from cbodept where id = {0})", deptId);
		List<CboOrgEntity> cboOrgEntityList = cboOrgService.queryByWhere(sql.toString());
		CboOrgEntity resultEntity = cboOrgEntityList.size()>0?cboOrgEntityList.get(0): (new CboOrgEntity());
		return ResponseResult.ok(resultEntity);
	}


	/**
	 * @author: wudaliang
	 * @date: 2022-01-20 获取ERP中的账期信息
	 * @description:
	 * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
	 * @modify:
	 */
	@GetMapping(value="/queryErpAccount")
	public ResponseResult<Object> queryErpAccount(@RequestParam Map<String ,Object> paraMap)
		throws Exception {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		Query query = new Query(paraMap);
		RestTemplate restTemplate = (RestTemplate) SpringUtil.getBean("restTemplate");
		String templateid= ParameterCache.getValue(PmSystemConst.ErpAccountTemplateId);
		String url = ParameterCache.getValue(PmSystemConst.DataServiceUrl);
		String token = ParameterCache.getValue(PmSystemConst.DataServiceToken);
		HttpHeaders headers = new HttpHeaders();
		List<Map> listDataMap=new ArrayList<>();
		HashMap<String, Object> queryParams = new HashMap<>();
		HashMap<String, Object> paramsMap = new HashMap<>();
		// 通过判断传参是否全部为空决定是否单独查询“款到发货”并添加到结果集中
		int paramsAllNullFlag = 0;
		// 拼接参数
		StringBuilder confirmtermname = new StringBuilder();

			// 防止只查询出后付
			confirmtermname.append("%付%");
			// 预付
			if(paraMap.containsKey("qry_AdvanceRatio")){
				String value = paraMap.get("qry_AdvanceRatio").toString();
				// 若预付非空才拼接第一个横杠
				if(!StringUtil.isEmpty(value)){
					confirmtermname.append(value).append("-");
				}else{
					paramsAllNullFlag++;
				}
			}else{
				paramsAllNullFlag++;
			}

			// 支付
			if(paraMap.containsKey("qry_PayRatio")){
				String value = paraMap.get("qry_PayRatio").toString();
			    if(!StringUtil.isEmpty(value)){
			    	confirmtermname.append(value);
				}else{
			    	confirmtermname.append("%");
			    	paramsAllNullFlag++;
				}
			}else{
				confirmtermname.append("%");
				paramsAllNullFlag++;
			}
			confirmtermname.append("(");

			// 货到/票到
			if (paraMap.containsKey("qry_DeliveryLimit")) {
				String value = paraMap.get("qry_DeliveryLimit").toString();
				if (!StringUtil.isEmpty(value)) {
					confirmtermname.append(value);
				} else {
					confirmtermname.append("%");
					paramsAllNullFlag++;
				}
			} else {
				confirmtermname.append("%");
				paramsAllNullFlag++;
			}
			confirmtermname.append(")-");

			//质保金
			if(paraMap.containsKey("qry_WarrantyMoney")){
				String value = paraMap.get("qry_WarrantyMoney").toString();
				if(!StringUtil.isEmpty(value)){
					confirmtermname.append(value);
				}else{
					confirmtermname.append("%");
					paramsAllNullFlag++;
				}
			}else{
				confirmtermname.append("%");
				paramsAllNullFlag++;
			}
			confirmtermname.append("(%)");
			paramsMap.put("confirmtermname",confirmtermname);

		// 模板id
		queryParams.put("templateid",templateid);
		// 请求头
		headers.add("token",token);
		headers.add("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
		queryParams.put("pageNum",0);
		queryParams.put("pageSize",0);
		// 若四个参数全部为空、没有传name参数时查询所有记录
		if(paramsAllNullFlag==4){
			paramsMap.put("confirmtermname", "%");
		}
		queryParams.put("paramsMap", paramsMap);
		HttpEntity httpEntity = new HttpEntity(queryParams, headers);
		ResponseEntity<JSONObject> response = restTemplate.postForEntity(url, httpEntity, JSONObject.class);
		if(response.getBody().getBooleanValue("success")==false){
			throw new Exception(response.getBody().getString("message"));
		}else{
			Map<String, Object> result = response.getBody().getJSONObject("result");
			List<Map> dataList =(List<Map>)result.get("dataList");
			// 总记录数
			int totalCount = ConvertUtil.convertToInt(result.get("totalCount"));
			//处理数据
			ConvertPayList(listDataMap,dataList,0,dataList.size()-1);
			List<Map> listResultMap= new ArrayList<>();
			int last =query.getCurrentPage() * query.getPageSize();
			if(last>dataList.size()){
				last=dataList.size();
			}
			for(int i = (query.getCurrentPage() - 1) * query.getPageSize() ; i < last; i++) {
				Map bomMap=listDataMap.get(i);
				listResultMap.add(bomMap);
			}

			Page pageInfo = new Page(listResultMap, dataList.size(), query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(pageInfo);
		}

	}

	/**
	 * @author: wudaliang
	 * @date: 2022-01-21
	 * @description: 调用ERP接口并处理账期信息
	 * @return: void
	 * @modify:
	 */
	public void ConvertPayList(List<Map> resultList,List<Map> paramList,int begin,int end){
		for(int i = begin; i<=end && i<paramList.size(); i++){
			Map<String,Object> itemMap = paramList.get(i);
			Map<String, Object> map = new HashMap<>();
			String name = ConvertUtil.convertToString(itemMap.get("name"));
			String code = ConvertUtil.convertToString(itemMap.get("code"));
			// 添加编码
			map.put("erpsourcecode", code);
			// 添加名称
			map.put("payname", name);
			// 分割name
			String[] arr = name.substring(2).split("\\-|\\(|\\)");
			// 去空
			List<String> valueList = new ArrayList<>();
			for (int j = 0; j < arr.length; j++) {
				if (!StringUtil.isEmpty(arr[j])) {
					valueList.add(arr[j]);
				}
			}
			if ("预付".equals(name.substring(0, 2)) && valueList.size() == 5){
				// 预付比例
				map.put("advanceRatio", valueList.get(0));
				// 支付比例
				map.put("payRatio", valueList.get(1));
				// 货到/票到
				map.put("deliveryLimit", valueList.get(2));
				// 质保比例
				map.put("warrantyMoney", valueList.get(3));
				// 质保期，只有客户档案才存ERP中获取的质保期，合同申请单中保存生成合同页面选择的编码
				map.put("warrantyPeriod", valueList.get(4));
				// 拼接描述字段
				StringBufferProxy paymethod = new StringBufferProxy();
				if (!"0".equals(valueList.get(0))) {
					paymethod.appendSingle("预付{0}%，", valueList.get(0));
				}
				if (!"0".equals(valueList.get(2))) {
					paymethod.appendSingle("票到{0}天，", valueList.get(2));
				}
				if (!"0".equals(valueList.get(1))) {
					paymethod.appendSingle("支付{0}%，", valueList.get(1));
				}
				if (!"0".equals(valueList.get(4))) {
					paymethod.appendSingle("质保期{0}天，", valueList.get(4));
				}
				if (!"0".equals(valueList.get(3))) {
					paymethod.appendSingle("质保金{0}%", valueList.get(3));
				}
				if ('，' == paymethod.toString().charAt(paymethod.length() - 1)) {
					map.put("paymethod", paymethod.toString().substring(0, paymethod.length() - 1));
				} else {
					map.put("paymethod", paymethod.toString());
				}
			}else if("后付".equals(name.substring(0, 2)) && valueList.size() == 4){
				// 支付比例
				map.put("payRatio", valueList.get(0));
				// 货到/票到
				map.put("deliveryLimit", valueList.get(1));
				// 质保比例
				map.put("warrantyMoney", valueList.get(2));
				// 质保期
				map.put("warrantyPeriod", valueList.get(3));
				// 拼接描述字段
				StringBufferProxy paymethod = new StringBufferProxy();
				if (!"0".equals(valueList.get(1))) {
					paymethod.appendSingle("票到{0}天，", valueList.get(1));
				}
				if (!"0".equals(valueList.get(0))) {
					paymethod.appendSingle("支付{0}%，", valueList.get(0));
				}
				if (!"0".equals(valueList.get(3))) {
					paymethod.appendSingle("质保期{0}天，", valueList.get(3));
				}
				if (!"0".equals(valueList.get(2))) {
					paymethod.appendSingle("质保金{0}%", valueList.get(2));
				}
				if ('，' == paymethod.toString().charAt(paymethod.length() - 1)) {
					map.put("paymethod", paymethod.toString().substring(0, paymethod.length() - 1));
				} else {
					map.put("paymethod", paymethod.toString());
				}
			}else{
				// 款到发货
				map.put("paymethod", name);
			}
			resultList.add(map);
		}
	}


	/**
	 * @author: wudaliang
	 * @date: 2022-02-12
	 * @param: paraMap
	 * @description: 项目开票时，如果项目只有一个合同，则返回该合同的账期信息。如果项目有多个合同，则返回审核通过的合同的账期信息
	 * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
	 * @modify:
	 */
	@GetMapping(value="/queryErpAccountByInvoice")
	public ResponseResult<Object> queryErpAccountByInvoice(@RequestParam Map<String ,Object> paraMap){
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		Query query = new Query(paraMap);
		if(paraMap.containsKey("projectidfrominvoice")){
			String projectid = ConvertUtil.convertToString(paraMap.get("projectidfrominvoice"));
			StringBufferProxy sql = new StringBufferProxy();
			// 查询该项目下的并且在  "扫描件审批"  节点审批通过的合同下的账期信息，合同不一定审批通过
			// （因为  "扫描件审批" 节点审批通过后，市场就去开票）
			sql.appendSingle("  projectid = '{0}'  and enabled=1 ",projectid);
			List<PmContractEntity> pmContractEntities = pmContractService
				.queryByWhere(sql.toString());

			List<PmContractEntity> operaContractEntities=new ArrayList<>();

			for (PmContractEntity pmContractEntity : pmContractEntities) {
				StringBufferProxy wheresql = new StringBufferProxy();
				// 项目合同审批中的"扫描件审批"节点ID
				String  aprovalnodeid= this.datacodeCache.getValueDynamic("ContractScannedNodeId",ConvertUtil.convertToString(pmContractEntity.getFlowid()), "code", "name");
				// 查询合同在"扫描件审批"节点是否涉审批通过
				wheresql.appendSingle(" sourceid='{0}' and nodeid='{1}' and sourcetype='{2}' and state = 2 ",pmContractEntity.getId(),aprovalnodeid,PmContractEntity.tableName);
				List<CboApprovalNodeInsEntity> cboApprovalNodeInsEntities = cboApprovalNodeInsService
					.queryByWhere(wheresql.toString());
				if(cboApprovalNodeInsEntities.size()>0){
					operaContractEntities.add(pmContractEntity);
				} else {
					// 兼容历史数据：股份、电力、科远、分公司等等组织的审批流程全部都调整过，有的老合同审批流程中没有"扫描件审批"节点，对于这种，查询审批流程中是否存在”结束“节点即可（也就是判断审批是否结束）
					wheresql.clear();
					wheresql.appendSingle(" sourceid='{0}'  and sourcetype='{1}' and  EXTENDFIELD2 ='结束' and state = 2 ",pmContractEntity.getId(),PmContractEntity.tableName);
					List<CboApprovalNodeInsEntity> cboApprovalNodeInsEntitiesJianRong = cboApprovalNodeInsService
						.queryByWhere(wheresql.toString());
					if(cboApprovalNodeInsEntitiesJianRong.size()>0){
						operaContractEntities.add(pmContractEntity);
					}
				}
			}
			ArrayList<HashMap> responseList = new ArrayList<>();
			for(PmContractEntity entity:operaContractEntities){
				HashMap<String, Object> map = new HashMap<>();
				map.put("paymethod",entity.getPaymethod());
				map.put("erpsourcecode",entity.getErpsourcecode());
				map.put("payname",entity.getPayname());
				responseList.add(map);
			}
			Page pageInfo = new Page(responseList, responseList.size(), query.getPageSize(),query.getCurrentPage());
			return ResponseResult.ok(pageInfo);
		}
		return null;
	}
}

